<?php

namespace app\store\controller\zzindb;

use alibabasdk\AlibabaClient;
use alibabasdk\AlibabaException;
use think\Config;
use think\Db;
use think\Request;
use think\View;

class Aliorder extends Alibasecontroller
{
    /** 商品分类初始化界面 */
    public function index(){

    }
    /** 查找全网最低价 */
    public function getGoodPrice(){
        echo '先根据商品id，选择规格id，地址：/index.php?s=/store/zzindb.aligoods/aliGoodDesArrPrint/gid/45678655172';
        $paramArr = $this->request->param();
        $gid = !empty($paramArr['gid']) ? $paramArr['gid'] : 0;
        $specid = !empty($paramArr['specid']) ? $paramArr['specid'] : 0;
        if($gid>0 && $specid>0){
            $addressArr = [
                'address'=>'韦曲街道福泽巷22号','phone'=>'18049001837','mobile'=>'18049001837',
                'fullName'=>'单肖','postCode'=>"000000",'townText'=>"",
                'areaText'=>'长安区', 'cityText'=>'西安市','provinceText'=>'陕西省',
            ];
            $goodPara = ['offerId'=>$gid, 'specId'=>$specid, 'quantity'=>200];
            $params = [
                "flow" => "", // fenxiao boutiquefenxiao
                "isvBizTypeStr" => "fenxiaoMedia",
                "addressParam"=>json_encode($addressArr),
                'cargoParamList'=>json_encode($goodPara)
            ];
            //先预览商品订单，获得最低价的flow
            $api = 'com.alibaba.trade:alibaba.createOrder.preview-1';
            $res = $this->getOldData($api, $params);
            echo '<hr><hr>';
            dump($res);
        }
    }
    /** 测试通过用户下单id号，进行阿里的订单提交---------------------------------------------------------------------------- */
    public function alicreOrd()
    {
        $paramArr = $this->request->param();
        $ordid = !empty($paramArr['ordid']) ? $paramArr['ordid'] : 0;
        $this->aliCreateOrder($ordid);
    }
    /** 提交商品创建订单数据到阿里巴巴 */
    private function aliCreateOrder($orderId)
    {
        if($orderId>0){
            // 查找订单包含哪些商品，并将商品id号返回
            $ordGoodsArr = Db::name('order_goods')->whereIn('order_id', $orderId)->select()->toArray();
            echo '<hr>0: 此订单共有'. count($ordGoodsArr) .'个商品：';
            if(count($ordGoodsArr)>0){
                $goodIdStr = $this->opmIdsArrStr($ordGoodsArr,'goods_id');
                $goodSkuIdStr = $this->opmIdsArrStr($ordGoodsArr,'goods_sku_id');
                //echo $goodIdStr.'****'.$goodSkuIdStr;

                // 通过返回的商品id号，在商品sku表中，查找真正的阿里巴巴商品id号
                $goodsArr = Db::name('goods')->whereIn('goods_id', $goodIdStr)->select()->toArray();
                $aliGoodsIdsArr = [];
                foreach($goodsArr as $perGood){
                    $perGood['net_from']==2 ? $aliGoodsIdsArr[]=$perGood['goods_id'] : "";
                }
                $goodsSkuArr = Db::name('goods_sku')->whereIn('goods_sku_id', $goodSkuIdStr)->select()->toArray();
                echo '<hr>1: 获得购买的商品sku信息，共'. count($goodsSkuArr) .'个：'; //print_r($goodsSkuArr);

                if(count($goodsSkuArr)>0){
                    $ableUseSkuIdArr = [];
                    foreach($goodsSkuArr as $key => $value){
                        if(in_array($value['goods_id'], $aliGoodsIdsArr) && $value['goods_no']!=''){
                            $ableUseSkuIdArr[] = $value['goods_sku_id'];
                        }
                    }
                    echo '<hr>2：可以下单的阿里skuID号数组，共'. count($ableUseSkuIdArr).'个：'; print_r($ableUseSkuIdArr);
                    // 通过阿里巴巴id进行下单
                    if(count($ableUseSkuIdArr)>0){
                        $addObj = Db::name('order_address')->where('order_id', $orderId)->find();
                        $this->runAliCreateOrdFun($goodsArr, $ordGoodsArr, $ableUseSkuIdArr, $addObj);
                    }
                }
            }
        }
        else{
            echo '未传递订单id';
        }
    }
    /** 将指定字符串id组成成单独数组字符串 */
    private function opmIdsArrStr($arr, $key)
    {
        $backArr = [];
        foreach($arr as $value){
            $backArr[] = $value[$key];
        }
        return implode(',', $backArr);
    }
    /** 最终可用的阿里巴巴的SkuIds数组 */
    private function runAliCreateOrdFun($goodsArr, $ordGoodsArr, $ableUseSkuIdArr, $addObj)
    {
        if(!empty($addObj['phone'])){
            $regionIdStr = implode(',', [$addObj['province_id'],$addObj['city_id'],$addObj['region_id']]);
            $regionArr = Db::name('region')->whereIn('id', $regionIdStr)->select()->toArray();
            $addressArr = [
                'address'=>$addObj['detail'],'phone'=>$addObj['phone'],'mobile'=>$addObj['phone'],
                'fullName'=>$addObj['name'],'postCode'=>"000000",'townText'=>"",
                'areaText'=>$this->getRegionName($regionArr,$addObj['region_id']),
                'cityText'=>$this->getRegionName($regionArr,$addObj['city_id']),
                'provinceText'=>$this->getRegionName($regionArr,$addObj['province_id']),
            ];
            echo '<hr>3: 地址信息：'; print_r($addressArr);



            $bigParaArr = [];
            $finalGoodNum = 0;
            foreach($ordGoodsArr as $vvv){
                if(in_array($vvv['goods_sku_id'], $ableUseSkuIdArr)){
                    $goodObj = $this->getNetGoodObj($goodsArr, $vvv['goods_id']);
                    $sellOpenUid = $goodObj['sellerOpenUid']!="" ? $goodObj['sellerOpenUid'] : "aaaa";
                    $cell = ['offerId'=>$goodObj['net_goodid'], 'specId'=>$vvv['goods_no'], 'quantity'=>$vvv['total_num']];

                    //将同一卖家的商品拆分创建订单
                    //$bigParaArr[$sellOpenUid][] = $cell;
                    //每个商品作为一个订单
                    $bigParaArr[] = $cell;

                    $finalGoodNum++;
                }
            }
            echo '<hr>4: 商家共'. count($bigParaArr) .'家，商品共'. $finalGoodNum .'个：'; print_r($bigParaArr);

            $aliMoney = 0;
            foreach($bigParaArr as $para){
                $params = [
                    "flow" => "", // fenxiao boutiquefenxiao
                    //"isvBizTypeStr" => "fenxiaoMedia",
                    "addressParam"=>json_encode($addressArr),
                    'cargoParamList'=>json_encode($para)
                ];
                echo '<hr>********************** 5：阿里下单传递的参数：'; print_r($params);

                // 先预览商品订单，获得最低价的flow
                $api = 'com.alibaba.trade:alibaba.createOrder.preview-1';
                $res = $this->getOldData($api, $params);
                $viewData = $res['orderPreviewResuslt'][0];
                //获得最低得价格，最低得去掉
                $cargoList = $viewData['cargoList'];
                $vipPrice = $cargoList[0]['finalUnitPrice'];
                $vipFlow = $viewData['flowFlag']!='' ? $viewData['flowFlag'] : 'boutiquefenxiao';
                echo "<hr><span style='color:#F00;font-weight:bold;'>本品最低价格：$vipPrice 元，下单渠道：$vipFlow </span>";

                // 根据返回得最低渠道进行下单
                $api22 = 'com.alibaba.trade:alibaba.trade.fastCreateOrder-1';
                $params22 = [
                    "flow" => $vipFlow,
                    "isvBizTypeStr" => "fenxiaoMedia",
                    "addressParam"=>json_encode($addressArr),
                    'cargoParamList'=>json_encode($para)
                ];
                $res22 = $this->getOldData($api22, $params22);
                echo '<hr><hr>';
                dump($res22);
            }

            // 阿里云下单成功后，修改订单状态，不能二次下单，将下单金额修改
            $orderId = $ordGoodsArr[0]['order_id'];
            echo '<hr>6：修改订单，避免重复下单：aliMoney：'. $aliMoney .'， orderId：'.$orderId;
        }
        else{
            echo '<hr>*************订单无联系人信息';
        }
    }
    /** 通过省市县id获取对应的名称 */
    private function getRegionName($regionArr, $id){
        $back = "";
        foreach($regionArr as $key => $value){
            if($value['id']==$id){
                $back = $value['name'];
                break;
            }
        }
        return $back;
    }
    /** 通过商品id查找商品net_goodid */
    private function getNetGoodObj($goodsArr, $gid){
        $back = "";
        foreach($goodsArr as $value){
            if($value['goods_id']==$gid){
                $back = $value;
                break;
            }
        }
        return $back;
    }

}
